//
//  main.swift
//  RegexHelper
//
//  Created by dayu on 15/6/5.
//  Copyright (c) 2015年 dayu. All rights reserved.
//

import Foundation

infix operator =~ {
    associativity none
    precedence 130
}

prefix operator ~/ {}

func =~(lhs: String, rhs: String) -> Bool {
    let helper: RegexHelper? = RegexHelper(rhs);
    if let tools = helper {
        return tools.match(lhs);
    }else {
        return false;
    }
}

func ~=(pattern: NSRegularExpression, input: String) -> Bool {
    return pattern.numberOfMatchesInString(input, options: nil, range: NSMakeRange(0, (input as NSString).length)) > 0;
}

prefix func ~/(pattern: String) -> NSRegularExpression {
    let regexExp = NSRegularExpression(pattern: pattern, options: nil, error: nil);
    if let regex = regexExp {
        return regex;
    }
    return NSRegularExpression();
}

let mailRegex = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
if "xxxxxx@163.com" =~ mailRegex {
    println("有效的邮箱地址");
}

let phoneRegex = "^1([3458])([0-9]{9}$)"
if "13000000000" =~ phoneRegex {
    println("有效的电话号码");
}

let contact = ("https://www.baidu.com", "xxxxxxx@163.com");

let siteRegex: NSRegularExpression = ~/"^(https?:\\/\\/)?(www.)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w\\.-]*)*\\/?$";
let emailRegex = ~/"^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$";

if contact.1 =~ mailRegex {
    println("邮箱有效");
}    

switch contact {
    case (siteRegex, emailRegex):
        println("网站和邮箱都有效");
    case (siteRegex, _):
        println("只有网站有效");
    case (_, emailRegex):
        println("只有邮箱有效");
    default:
        println("都无效");
}

let userNameRegex = ~/"^[a-z0-9_-]{3,16}$";
let PasswordRegex = ~/"^[a-z0-9A-Z_-]{6,18}$";

let account = ("yourName", "Macheal");
switch account {
case (userNameRegex, PasswordRegex):
    println("帐号和密码合法");
case (userNameRegex, _):
    println("密码不合法");
case (_, PasswordRegex):
    println("帐号不合法");
default:
    println("帐号和密码都不合法");
}
